<template>
    <div ref="container">
        <a-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading"
            :getContainer="() => $refs.container" :maskStyle="{ top: '93px', left: '154px' }"
            :wrapClassName="wrapClassNameInfo()" :mask="isDesktop()" :maskClosable="false" @ok="handleOk"
            @cancel="handleCancel" cancelText="关闭" style="top: 5%; height: 85%">
            <template slot="footer">
                <a-button key="back" v-if="isReadOnly" @click="handleCancel"> 关闭 </a-button>
            </template>
            <a-spin :spinning="confirmLoading">
                <a-form-model :model="form" ref="ruleForm" :rules="rules" id="messageModal">
                    <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="msgTitle">
                        <a-input placeholder="请输入标题" v-model="form.msgTitle" />
                    </a-form-model-item>
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="消息内容" prop="msgContent">
                        <a-textarea :rows="4" placeholder="请输入消息内容" v-model="form.msgContent" />
                    </a-form-model-item>
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发送方式" prop="userType">
                        <a-radio-group v-model="form.userType" @change="radioChange">
                            <a-radio value="0">
                                机构
                            </a-radio>
                            <a-radio value="1">
                                角色
                            </a-radio>
                        </a-radio-group>
                    </a-form-model-item>

                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="机构" prop="orgId"
                        v-show="form.userType == '0'">
                        <a-tree-select style="width: 100%" :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                            allow-clear :treeData="orgaTree" placeholder="请选择机构" @change="(e)=>treeSelect(e,'org')"
                            v-model="form.orgId">
                        </a-tree-select>
                    </a-form-model-item>
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色列表" prop="role"
                        v-show="form.userType == '1'">
                        <a-select placeholder="请选择角色" :dropdownMatchSelectWidth="false"
                            @change="(e)=>treeSelect(e,'role')" v-model="form.role">
                            <a-select-option v-for="(item, index) in roleList" :key="item.id" :value="item.id">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户列表" prop="userIds">
                        <a-select placeholder="请先选择机构/角色" v-model="form.userIds" mode="multiple" :maxTagCount="8"
                            :dropdownMatchSelectWidth="false">
                            <a-select-option v-for="(item, index) in cUserList" :key="index" :value="item.id">
                                {{ item.userName }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>

                    <!-- <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户列表" prop="userIds"
                        v-if="form.userType == '1'">
                        <a-select placeholder="请选择用户" v-model="form.userIds" mode="multiple" :maxTagCount="8"
                            :dropdownMatchSelectWidth="false">
                            <a-select-option v-for="(item, index) in roleUserList" :key="item.id" :value="item.id">
                                {{ item.username }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item> -->

                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发送方式" prop="timeSwitch">
                        <a-radio-group v-model="form.timeSwitch">
                            <a-radio value="0">
                                立即发送
                            </a-radio>
                            <a-radio value="1">
                                定时发送
                            </a-radio>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item v-if="form.timeSwitch == '1'" :labelCol="labelCol" :wrapperCol="wrapperCol"
                        label="发送时间" prop="sendTime">
                        <j-date placeholder="请选择发送时间" v-model="form.sendTime" style="width:100%" :show-time="true" />
                    </a-form-model-item>
                </a-form-model>
            </a-spin>
        </a-modal>
    </div>
</template>
<script>
import pick from 'lodash.pick'
import Vue from 'vue'
import JSelectPosition from '@/components/jeecgbiz/JSelectPosition'
import JDate from '@/components/jeecg/JDate'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction, postAction, putAction } from '@/api/manage'
import {
    addUser,
    editUser,
    queryOrganizationTreeList,
    roleAllList,
    depAllList,
    queryUserOrganizationTreeList,
} from '@/api/api'
import { disabledAuthFilter } from '@/utils/authFilter'
import { autoJumpNextInput } from '@/utils/util'
import { mixinDevice } from '@/utils/mixin'
import JImageUpload from '../../../components/jeecg/JImageUpload'
export default {
    name: 'MessageModal',
    mixins: [mixinDevice],
    components: {
        JImageUpload,
        JSelectPosition,
        JDate,
    },
    data() {
        return {
            title: '操作',
            visible: false,
            modalWidth: 800,
            drawerWidth: 700,
            orgaTree: [],
            departmentList: [],
            userList: [],
            roleList: [],
            userId: '', //保存用户id
            isReadOnly: false,
            disableSubmit: false,
            dateFormat: 'YYYY-MM-DD',
            rules: {
                msgTitle: [
                    {
                        required: true,
                        message: '请输入标题!',
                        trigger: 'change',
                    },
                ],
                msgContent: [
                    {
                        required: true,
                        message: '请输入消息内容!',
                        trigger: 'change',
                    },
                ],
                sendTime: [
                    {
                        required: true,
                        message: '请选择发送时间!',
                        trigger: 'change',
                    },
                ],
                // orgId: [
                //     {
                //         required: true,
                //         message: '请选择机构!',
                //         trigger: 'change',
                //     },
                // ],
                userIds: [
                    {
                        required: true,
                        message: '请选择用户!',
                        trigger: 'change',
                    },
                ],
            },
            model: {},
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
            uploadLoading: false,
            confirmLoading: false,
            headers: {},
            form: {
                msgTitle: undefined,
                msgContent: undefined,
                orgId: undefined,
                userIds: [],
                timeSwitch: '0',
                sendTime: undefined,
                type: '通知',
                userType: '0',
                role: undefined,
            },
            isRoleIdHead: false,
            roleUserList: [],
            roleList: [],
            // cUserList:[]
        }
    },
    created() {
        const token = Vue.ls.get(ACCESS_TOKEN)
        this.headers = { 'X-Access-Token': token }
    },
    computed: {
        cUserList() {
            return this.form.userType == '0' ? this.userList : this.roleUserList
        },
    },

    methods: {
        add() {
            this.edit({ ...this.form })
        },
        edit(record) {
            this.loadOrgaData()
            this.userId = record.id
            this.visible = true
            this.model = Object.assign({}, record)
            this.$nextTick(() => {
                this.$refs.ruleForm.resetFields()
                // pick(this.model, 'msgTitle', 'msgContent', 'orgId', 'userIds', 'timeSwitch', 'sendTime')

                // this.$refs.ruleForm.setFieldsValue(
                //     pick(this.model, 'msgTitle', 'msgContent', 'orgId', 'userIds', 'timeSwitch', 'sendTime')
                // )
                autoJumpNextInput('messageModal')
            })
        },
        close() {
            this.$emit('close')
            this.visible = false
            this.disableSubmit = false
        },
        handleOk() {
            const that = this
            // 触发表单验证
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    that.confirmLoading = true
                    let formData = Object.assign(this.model, this.form)
                    let obj
                    let params = {}
                    params.userIds = this.form.userIds
                    params.msg =
                        this.form.timeSwitch == '0'
                            ? pick(formData, 'msgTitle', 'msgContent', 'type', 'timeSwitch')
                            : pick(formData, 'msgTitle', 'msgContent', 'type', 'timeSwitch', 'sendTime')
                    if (!this.model.id) {
                        obj = postAction('/msg/insertMsg', params)
                    } else {
                        obj = putAction('/msg/update', params)
                    }
                    obj.then((res) => {
                        if (res.code === 200) {
                            that.$emit('ok')
                            that.close()
                        } else {
                            that.$message.warning(res.data.message)
                        }
                    }).finally(() => {
                        that.confirmLoading = false
                    })
                }
            })
        },
        handleCancel() {
            this.close()
        },
        loadOrgaData() {
            let that = this
            let params = {}
            params.id = ''
            queryOrganizationTreeList(params).then((res) => {
                if (res) {
                    that.orgaTree = res
                }
            })
            // getAction('/user/queryUserListByRoleId', { roleId: 41 }).then((res) => {
            //     if (res) {
            //         this.roleUserList = res.data.users.map((item) => ({ id: item.id, userName: item.username }))
            //     }
            // })

            getAction('/role/allList').then((res) => {
                if (res) {
                    this.roleList = res
                }
            })
        },
        radioChange(e) {
            this.form.userIds = []
        },
        async treeSelect(e, type) {
            if (!e) {
                this.form.userIds = []
                return
            }
            if (type == 'org') {
                let res = await getAction(`/user/getUserListByOrgId`, { orgId: e })
                if (res) {
                    this.userList = res
                    this.form.userIds = res.map((item) => item.id)
                }
            } else if (type == 'role') {
                let res = await getAction('/user/queryUserListByRoleId', { roleId: e })
                if (res) {
                    this.roleUserList = res.data.users.map((item) => ({ id: item.id, userName: item.username }))
                    this.form.userIds = this.roleUserList.map((item) => item.id)
                }
            }
        },
    },
}
</script>

<style scoped>
</style>